import {
    forwardRef,
    useCallback,
    useContext,
    useEffect,
    useImperativeHandle,
    useRef,
    useState
} from 'react';
import {Table, TableProps} from 'antd';
import {componentMap} from '@/components/SlForm/componentMap';
import {SlTableProps, TableRowData} from '@/types/table';
import style from './index.module.scss';
import {StyleContext} from '@/context/style-context.tsx';
import {getTableComponentProps} from '@/components/SlTable/helper.ts';
import {getRealValue} from "@/components/SlForm/helper.ts";

const SlTable = forwardRef(
    function SlTableComponent<T extends TableRowData>(
        props: SlTableProps<T>,
        ref: any
    ) {
        const {
            tableData,
            tableHeader,
            slots,
            isLoading,
            pagination,
            handlers,
            scroll,
            status,
            queryList,
            total,
            current,
            pageSize
        } = props;
        const {namespace} = useContext(StyleContext);
        const [tableColumns, setTableColumns] = useState<
            TableProps<any>['columns']
        >([]);
        const defaultPagination = {
            position: ['none', 'bottomCenter']
        }
        const [tableHeight, setTableHeight] = useState<number>(0);
        const tableRef = useRef<any>(null);
        // 添加 resize 监听器
        const resizeObserver = useRef<ResizeObserver | null>(null);
        // 计算表格高度
        const calculateTableHeight = useCallback(() => {
            if (tableRef.current) {
                // 获取容器可用高度
                const containerHeight =
                    tableRef.current.parentElement?.clientHeight || 0;
                const paginationLen =
                    pagination && pagination.position
                        ? pagination.position.filter(
                            (ele: any) => ele !== 'none',
                        ).length
                        : 0;
                // 减去分页高度（如果分页可见）
                const paginationHeight = paginationLen * 32; // 约64px，分页器标准高度
                // 减去表头高度
                const headerHeight = 55; // 默认表头高度，可根据需要调整
                // 减去内边距/外边距
                const paddingMargin = 48;
                // 计算表格主体可用高度
                const bodyHeight =
                    containerHeight -
                    paginationHeight -
                    headerHeight -
                    paddingMargin;

                // 设置最小高度
                const finalHeight = Math.max(bodyHeight, 200);
                setTableHeight(finalHeight);
            }
        }, [pagination]);
        // 监听父容器尺寸变化
        useEffect(() => {
            if (!tableRef.current) return;
            calculateTableHeight();
            // 使用 ResizeObserver 监听父容器尺寸变化
            resizeObserver.current = new ResizeObserver(() => {
                calculateTableHeight();
            });

            const parentElement = tableRef.current.parentElement;
            if (parentElement) {
                resizeObserver.current?.observe(parentElement);
            }
            return () => {
                if (resizeObserver.current) {
                    resizeObserver.current?.disconnect();
                }
            };
        }, [calculateTableHeight]);
        useEffect(() => {
            calculateTableHeight()
            dealTableColumns();
        }, [tableHeader, tableData]);
        useImperativeHandle(ref, () => ({}));
        const screenTableColumns = (data: any[]) => {
            return data.map((header) => {
                const column = {
                    ...header,
                    key: `header-${header.field}-${Date.now()}`,
                    dataIndex: header.field,
                    title: header.label,
                };
                const hasComponent = header.component && componentMap[header.component];
                if (hasComponent) {
                    const Component: any = componentMap[header.component];
                    column['render'] = (value: any, record: any, index: any) => {
                        const componentProps = getTableComponentProps({
                            item: header,
                            initialValues: record,
                            handlers,
                            slots,
                            status
                        });
                        const formType = header.formType ? header.formType : "edit";
                        return formType === "edit" ? (
                            <Component
                                key={header.field}
                                {...componentProps}
                            ></Component>
                        ) : getRealValue(header, value);
                    };
                } else if (slots && slots[header.field]) {
                    column['render'] = (
                        value: any,
                        record: any,
                        index: number,
                    ) =>
                        slots[header.field]({
                            row: record,
                            header,
                            rowIndex: index,
                            value,
                        });
                } else {
                    column['render'] = (value: any, record: any, index: number) => value ? value : '--'
                }
                if (header.children && header.children.length) {
                    column['children'] = screenTableColumns(header.children);
                }
                return column;
            });
        };
        const dealTableColumns = () => {
            const columns: TableProps['columns'] =
                screenTableColumns(tableHeader);
            setTableColumns(columns);
        };
        if (!tableColumns || !tableColumns.length) {
            return null;
        }
        // 添加滚动配置
        const tableScroll =
            tableHeight > 0
                ? {
                    x: 'max-content',
                    y: tableHeight,
                }
                : {x: 'max-content'};
        return (
            <div
                ref={tableRef}
                style={{
                    height: '100%',
                }}
            >
                <Table<T>
                    className={style[`${namespace}-table`]}
                    loading={isLoading}
                    columns={tableColumns}
                    dataSource={tableData}
                    pagination={{
                        current: queryList?.current,
                        pageSize: queryList?.size,
                        total: total,
                        showSizeChanger: true,
                        onChange: (page: number, size: number) => {
                            console.log('页码改变:', page, '每页数量:', size);
                            if (handlers && handlers["handleTableChange"]) {
                                handlers["handleTableChange"]({
                                    item: {
                                        field: "tableChange"
                                    },
                                    value: {
                                        current: page,
                                        pageSize: size
                                    }
                                })
                            }
                        },
                        ...defaultPagination,
                        ...pagination
                    } as any}
                    scroll={{
                        ...tableScroll,
                        ...scroll,
                    }}
                />
            </div>
        );
    },
) as <T extends TableRowData>(props: SlTableProps<T> & { ref?: React.ForwardedRef<any> }) => React.ReactElement;

export default SlTable;
